package com.gdth.bank;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.baidu.mapapi.SDKInitializer;
import com.gdth.bank.utils.DeviceIdUtil;
import com.gdth.bank.utils.SharedPreferencesUtil;
import com.gdth.core.widget.BaseApplication;
import com.gdth.database.MySQLiteOpenHelper;
import com.gdth.database.bean.DaoMaster;
import com.gdth.database.bean.DaoMaster.OpenHelper;
import com.gdth.database.bean.DaoSession;
import com.gdth.database.bean.TAppYh;
import com.gdth.model.ImageItem;
import com.gdth.resource.Constant;
import com.gdth.utils.GsonUtil;
import com.tencent.bugly.crashreport.CrashReport;
import com.gdth.bank.utils.AppUtil;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;

public class BankApplication extends BaseApplication {

	public static BankApplication mInstance;
	private static DaoMaster daoMaster;
	private static DaoSession daoSession;

	public String url;
	public String ip;
	public int port;
	public String token;

	public TAppYh currentUser;

	@Override
	public void onCreate() {
		super.onCreate();
		CrashReport.initCrashReport(getApplicationContext(), "320e149677", false); 
		CrashReport.putUserData(getApplicationContext(), "FaBuLeiXing", Constant.FaBuLeiXing);
		SDKInitializer.initialize(getApplicationContext());
		initConfig();
		if(mInstance == null) {
			mInstance = this;
			//添加页面快捷方式
			addDesktopMenu(getString(R.string.app_name), SplashScreenActivity.class.getName(), R.drawable.ic_launcher);

		}
		if (this.mFirst) {
			String deviceId = this.getDeviceId();
			SharedPreferencesUtil.saveSharePreference(this, AppUtil.SHARE_Application, AppUtil.SHARE_DATA_Device, deviceId);
		}
		//BuildConfig
		initNotification();
	}

	/**
	 * return DaoMaster
	 * 
	 * @param
	 */
	public static DaoMaster getDaoMaster() {

//		daoMaster = new DaoMaster(helper.getWritableDatabase());
		if (daoMaster == null) {
			MySQLiteOpenHelper helper = new MySQLiteOpenHelper(BankApplication.mInstance.getBaseContext(), Constant.DB_NAME,
					null);
//			OpenHelper helper = new DaoMaster.DevOpenHelper(BankApplication.mInstance.getBaseContext(), Constant.DB_NAME, null);
			if(Constant.isOpenLog){
				daoMaster = new DaoMaster(helper.getWritableDb());
			}else{
				daoMaster = new DaoMaster(helper.getEncryptedWritableDb(Constant.dataBasePw));
			}
//			daoMaster = new DaoMaster(helper.getWritableDb());
		}
		return daoMaster;
	}

	/**
	 * return DaoSession
	 * 
	 * @param
	 */
	public static DaoSession getDaoSession() {
		if (daoSession == null) {
			if (daoMaster == null) {
				daoMaster = getDaoMaster();
			}
			daoSession = daoMaster.newSession();
		}
		return daoSession;
	}

	public void initConfig() {
//		if (AppUtil.isApkDebugable(this)) {
			url = Constant.url;
			ip = Constant.ip;
//			port = Constant.port_test;
//		} else {
//			url = Constant.url;
//			ip = Constant.ip;
//			port = Constant.port;
//		}
	} 

	/**
	 * 根据不同的tab类型获取菜单内容
	 * @param context
	 * @param type
	 * @return
	 */
	public static List<ImageItem> getMenuList(Context context, String type){
		String path = type + "/menu.xml";
		List<ImageItem> mList = new ArrayList<ImageItem>();
		InputStream ins = null;
		try {
			ins = context.getResources().getAssets().open(path);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		DocumentBuilderFactory factory = null;
		DocumentBuilder builder=null;
		Document document=null;

		try {
			factory = DocumentBuilderFactory.newInstance();;
			builder=factory.newDocumentBuilder();

			document=builder.parse(ins);

			//获取全部image 元素节点
			NodeList nodeAttributes=(NodeList) document.getElementsByTagName("type");

			int nodeLength = nodeAttributes.getLength();

			for(int i=0 ; i < nodeLength; i++){
				Element mElement = (Element) (nodeAttributes.item(i));

				String id = mElement.getAttribute("key");
				String name = mElement.getAttribute("name");
				String imagename = mElement.getAttribute("imagename");
				String types = mElement.getAttribute("type");

				ImageItem model = new ImageItem();
				model.setKey(id);
				model.setImg(type + "/" +imagename);
				model.setValue(name);
				model.setType(Integer.valueOf(types));

				mList.add(model);
			}
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); 
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return mList;
	}

	/**
	 * 获取登录状态
	 * @return
	 */
	public static boolean getAppState(){
		return SharedPreferencesUtil.getSharePreferencesByKeyForBoolean(BankApplication.mInstance.getBaseContext(), AppUtil.SHARE_Application, AppUtil.SHARE_LOGIN_STATE);
	}

	/**
	 * 设置登录状态
	 * @param state
	 */
	public static void setAppState(boolean state){
		Map<String, Object> maps = new HashMap<String, Object>();

		maps.put(AppUtil.SHARE_LOGIN_STATE, state);

		SharedPreferencesUtil.saveSharePreferences(BankApplication.mInstance.getBaseContext(), AppUtil.SHARE_Application, maps);
	}


	/**
	 * 获取当前登录用户的json
	 * @return
	 */
	public String getCurrentUserForJson() {
		String json = SharedPreferencesUtil.getSharePreferencesByKey(this, AppUtil.SHARE_LOGIN_TAG, AppUtil.SHARE_DATA_USER);
		if (json == null || json.equals("") || json.equals("[]")) {

		}

		return json;
	}

	/**
	 * 获取用户信息
	 * @return
	 */
	public TAppYh getCurrentUser(){
		String json = SharedPreferencesUtil.getSharePreferencesByKey(this, AppUtil.SHARE_LOGIN_TAG, AppUtil.SHARE_DATA_USER);
		if (json == null || json.equals("") || json.equals("[]")) {

		}
		TAppYh user = GsonUtil.getGson().fromJson(json, TAppYh.class);

		return user;
	}

	public String getDeviceByShare() {
		String device = SharedPreferencesUtil.getSharePreferencesByKey(this, AppUtil.SHARE_Application, AppUtil.SHARE_DATA_Device);
		if (device == null || device.equals("") || device.equals("[]")) {
			device = getDeviceId();
			SharedPreferencesUtil.saveSharePreference(this, AppUtil.SHARE_Application, AppUtil.SHARE_DATA_Device, device);
		}

		return device;
	}

	/**
	 * 获取手机机器码
	 * @return
	 */
	/**
	 * 获取手机机器码
	 * @return
	 */
	@SuppressLint("MissingPermission")
	public String getDeviceId(){
		final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
		String tmDevice = null;
		String tmSerial = null;
		final String androidId;
		try {
			tmDevice = tm.getDeviceId();
		} catch (Exception e) {

		}

		if (tmDevice == null) {
			try {
				tmDevice = tm.getSimSerialNumber();
			} catch (Exception e) {

			}
		}
		androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
		//		UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
		//		String uniqueId = deviceUuid.toString();
		if (tmDevice == null) 
			tmDevice = androidId;

		if(androidId == null)
			tmDevice = DeviceIdUtil.getDeviceId(this);
		return tmDevice;
	}
	//	public String getDeviceId(){
	//		final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
	//		String tmDevice,tmSerial,tmPhone,androidId;
	//		tmDevice = "" + tm.getDeviceId();
	//		tmSerial = "" + tm.getSimSerialNumber();
	//		androidId ="" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
	//		UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
	//		String uniqueId = deviceUuid.toString();
	//		return uniqueId;
	//	}

	/**
	 * 退出所有activity
	 */
	@Override
	public void finishAll() {
		if (isLogin) {
			for(Activity act : activityList) { 
				if(!act.isFinishing()){ 
					act.finish(); 
				} 
			} 
			activityList = null;
			isLogin = false;
			final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());  
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
			startActivity(intent);  
		}
	}

	private Notification.Builder messageNotification;
	private NotificationManager mNotificationManager;
	private int messageNotificationID = 1000;

	private void initNotification(){
		//        messageNotification = new NotificationT.Builder(this.getApplicationContext());
		//        messageNotification.setContentInfo("APP服务");
		//        messageNotification.setContentText("APP启动");
		//        messageNotification.setContentTitle("攸县农商行");
		//        messageNotification.setSmallIcon(R.drawable.ic_launcher);
		//        messageNotification.setTicker("新消息");
		//        messageNotification.setAutoCancel(true);
		//        messageNotification.setWhen(System.currentTimeMillis());
		//
		//        mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
	}

	public void pushNotificationText(String val) {
		// TODO Auto-generated method stub
		//		messageNotification.setContentText(val);
		//        NotificationT notification = messageNotification.build();
		//        mNotificationManager.notify(messageNotificationID, notification);
	}
}
